<!-- AvatarCropperThumbnail.vue -->
<template>
  <div class="user-info-head">
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      @close="closeDialog"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '400px' }">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '200px' }">
          <div class="avatar-upload-preview">
            <img :src="options.previews.url" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button>
              选择
              <el-icon class="el-icon--right"><Upload /></el-icon>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{ span: 1, offset: 2 }" :md="2">
          <el-button :icon="Plus" @click="changeScale(1)" />
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button :icon="Minus" @click="changeScale(-1)" />
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button :icon="RefreshLeft" @click="rotateLeft" />
        </el-col>
        <el-col :lg="{ span: 1, offset: 1 }" :md="2">
          <el-button :icon="RefreshRight" @click="rotateRight" />
        </el-col>
        <el-col :lg="{ span: 2, offset: 6 }" :md="2">
          <el-button type="primary" @click="uploadImg">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, inject, getCurrentInstance } from "vue";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";
import { ElMessage as message } from "element-plus";
import {
  Upload,
  Plus,
  Minus,
  RefreshLeft,
  RefreshRight,
} from "@element-plus/icons-vue";
import { uploadFiles } from "@/api/business/upload";
import { useUserStore } from "@/store/modules/user";
import { updatePhoto, getPhotoListByType } from "@/api/business/sperm";

/* -------------------- 事件 & 属性 -------------------- */
const emits = defineEmits<{
  closeDialog: [];
}>();

const props = defineProps<{
  visiable: boolean;
  donorId: string;
  userName: string;
}>();

/* -------------------- 依赖注入 -------------------- */
const userId = inject<string>("userId");

/* -------------------- 仓库 -------------------- */
const userStore = useUserStore();

/* -------------------- 全局实例 -------------------- */
const { proxy } = getCurrentInstance()!;

/* -------------------- 状态 -------------------- */
const open = ref(false);
const title = ref("修改缩略图");

/* 裁剪配置 */
const options = reactive({
  img: "",
  autoCrop: true,
  autoCropWidth: 300,
  autoCropHeight: 200,
  fixedBox: true,
  outputType: "png" as const,
  filename: "avatar",
  previews: {} as Record<string, any>,
});

/* -------------------- 方法 -------------------- */
const requestUpload = () => {
  /* 覆盖默认上传，空实现 */
};

const rotateLeft = () => {
  (proxy?.$refs.cropper as any).rotateLeft();
};

const rotateRight = () => {
  (proxy?.$refs.cropper as any).rotateRight();
};

const changeScale = (num: number) => {
  (proxy?.$refs.cropper as any).changeScale(num);
};

const beforeUpload = (file: File) => {
  if (!file.type.startsWith("image/")) {
    message.error("请上传 JPG / PNG 等图片格式");
    return false;
  }
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    options.img = reader.result as string;
    options.filename = file.name;
  };
  return false; // 手动控制上传
};

const uploadImg = () => {
  (proxy?.$refs.cropper as any).getCropBlob((data: Blob) => {
    const formData = new FormData();
    formData.append("files", data, options.filename);
    const uploadUrl = `/business/photo/uploads?username=${props.userName}`;
    uploadFiles(formData, uploadUrl).then((res) => {
      updateForm({
        photoUrls: res.urls,
        basicId: props.donorId,
        photoType: "缩略图",
      });
    });
  });
};

const updateForm = async (form: {
  photoUrls: string;
  basicId: string;
  photoType: string;
}) => {
  const resp = await updatePhoto(form);
  if (resp.code === 200) {
    message.success("上传成功");
    closeDialog();
  } else {
    message.error("上传失败");
  }
};

const realTime = (data: any) => {
  options.previews = data;
};

const closeDialog = () => emits("closeDialog");

/* -------------------- 监听 -------------------- */
watch(
  () => props.visiable,
  (val) => {
    open.value = val;
    if (val) {
      getPhotoListByType({ donorId: props.donorId , photoType:'缩略图'}).then((res) => {
        options.img = res.rows?.[0]?.photoUrl || "";
      });
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.user-info-head {
  position: relative;
  display: inline-block;
  height: 200px;
}

.user-info-head:hover:after {
  content: "+";
  position: absolute;
  inset: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 110px;
}

.avatar-upload-preview {
  width: 317px;
  height: 200px;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
